package alik.notes.server.persistence;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import alik.notes.shared.data.Note;

public class NotesPersistence {

	public static List<Note> queryNotes(String userId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(NotePersistable.class, "userId == u");
		q.declareParameters(String.class.getName() + " u");
		q.setOrdering("lastEditDate");
		List<NotePersistable> notes = extracted(userId, q);

		return PersistenceTransformer.transform(notes);
	}

	@SuppressWarnings("unchecked")
	private static List<NotePersistable> extracted(String userId, Query q) {
		return (List<NotePersistable>) q.execute(userId);
	}

	public static void addNote(Note note, String userId) {
		note = PersistenceTransformer.transform(note, userId);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(note);
		} finally {
			pm.close();
		}
	}

}
